package com.jd.cs.controller;

import com.jd.cs.anotation.NotRepeatSubmit;
import com.jd.cs.common.MD5Util;
import com.jd.cs.error.ErrorCode;
import com.jd.cs.exception.APIException;
import com.jd.cs.service.MemTokenService;
import com.jd.cs.vo.AccessToken;
import com.jd.cs.vo.AppInfo;
import com.jd.cs.vo.TokenInfo;
import com.jd.cs.vo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-06-22
 */
@RestController
@RequestMapping("/mem_token")
public class TokenController {
    private final static Logger logger = LoggerFactory.getLogger(TokenController.class);

    @Resource
    MemTokenService memTokenService;

    /**
     * API Token
     *
     * @param sign
     * @return
     */
    @PostMapping("/api_token")
    public AccessToken apiToken(String appId, @RequestHeader("timestamp") String timestamp, @RequestHeader("sign") String sign) {

        // 1. 根据appId查询数据库获取appSecret
        AppInfo appInfo = new AppInfo("1", "12345678954556");

        // 2. 校验签名
        String signString = timestamp + appId + appInfo.getKey();
        String signature = MD5Util.encode(signString);
        logger.info(signature);

        boolean equals = signature.equals(sign);
        if (!equals) {
            throw new APIException(ErrorCode.E_20001);
        }

        return memTokenService.saveToken(TokenInfo.TokenType.API, appInfo, null);
    }


    @NotRepeatSubmit
    @PostMapping("user_token")
    public UserInfo userToken(String username, String password) {
        // 根据用户名查询密码, 并比较密码(密码可以RSA加密一下)
        UserInfo userInfo = new UserInfo(username, "81255cb0dca1a5f304328a70ac85dcbd", "111111");
        String pwd = password + userInfo.getSalt();
        String passwordMD5 = MD5Util.encode(pwd);

        if (!passwordMD5.equals(userInfo.getPassword())) {
            throw new APIException(ErrorCode.PARAMETER_ERROR);
        }

        // 2. 保存Token
        AppInfo appInfo = new AppInfo("1", "12345678954556");
        AccessToken accessToken = memTokenService.saveToken(TokenInfo.TokenType.USER, appInfo, userInfo);
        userInfo.setAccessToken(accessToken);
        return userInfo;
    }

}
